const db = require('../db/index')

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
const moment = require('moment')

//登录处理函数
exports.login = (req,res)=>{
    console.log(req.body)
    //数据查询语句
    db.query('select * from users where username=?',req.body.username,(err,result)=>{
      if(err) return res.send({
        code:500,
        message:err,
        data:{}
      })

      if(result.length!==1) return res.send({
        code:500,
        mesasge:'查无此人,登录失败！',
        data:{}
      })

      const compareResult = bcrypt.compareSync(req.body.password,result[0].password)

      if(!compareResult) return res.send({
        code:500,
        mesasge:'登录失败密码错误',
        data:{}
      })
      
      //生成token字段
      const user = {
        ...result[0],
        password:'',
        avatar:''
      }
      //对用户信息进行加密 生成token字段
      const tokenstr = jwt.sign(user,config.jwtSecretKey,{expiresIn:'10h'})
      res.send({
        code:200,
        message:'登录成功',
        data:{
            token:'Bearer '+ tokenstr
        }
      })
    })
   

}

//注册处理函数
exports.reglogin = (req,res)=>{
    db.query('select * from users where username=?',req.body.username,(err,result)=>{
        if(err) return res.send({
            code:500,
            message:err,
            data:{}
        })
        if(result.length>0){
            return res.send({
                code:500,
                mesasge:'用户名已被占用，请更换后重试！',
                data:{}
            })
        }
        //对密码加密
        req.body.password = bcrypt.hashSync(req.body.password,10)

        db.query('insert into users set?',{username:req.body.username,password:req.body.password,create_time:moment().format('YYYY-MM-DD HH:mm:ss')},(err,result)=>{
            if(err) return res.send({
                code:500,
                message:err,
                data:{}
            })
            if(result.affectedRows !==1){
                return res.send({
                    code:500,
                    message:'注册用户失败',
                    data:{}
                })
            }
            res.send({
                code:200,
                message:"注册成功",
                data:{}
            })
        })

    })
    
}